package com.gy.controller.research;

import com.alibaba.excel.EasyExcel;
import com.gy.config.BaiduOcrConfig;
import com.gy.controller.assistant.utils.PdfExtractUtil;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.research.Longitudinal;
import com.gy.query.LongitudinalQuery;
import com.gy.result.Result;
import com.gy.service.LongitudinalService;
import com.gy.vo.PageVO;
import com.gy.vo.SimpleLongitudinalVO;
import com.gy.vo.completed.CompletedLongitudinalVO;
import com.gy.vo.summary.LongitudinalVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/longitudinal")
@Api(tags = "纵向课题接口")
@CrossOrigin
public class LongitudinalController {

    @Autowired
    private LongitudinalService longitudinalService;

    @Autowired
    private PdfExtractUtil pdfExtractUtil;
    @Autowired
    private BaiduOcrConfig baiduOcrConfig; // 百度OCR工具类（与工具类一致）

    /**
     * 根据openid分页查看某个人的纵向课题
     */
    @PostMapping("/get/longitudinal")
    @ApiOperation("根据openid查看某个人的纵向课题材料")
    public Result<PageVO<Longitudinal>> getPapers(@RequestBody LongitudinalQuery longitudinalQuery) {
        return longitudinalService.getLongitudinal(longitudinalQuery);
    }

    /**
     * 根据纵向课题id主键删除纵向课题
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据其他id主键删除纵向课题")
    public Result deleteById(@PathVariable Long id) {
        return longitudinalService.removeLongitudinalById(id);
    }

    /**
     * 根据id主键查看纵向课题
     */
    @GetMapping("/getById/{id}")
    @ApiOperation("根据id主键查看纵向课题")
    public Result<Longitudinal> getLongitudinalById(@PathVariable Long id) {
        Longitudinal longitudinal = longitudinalService.getLongitudinalById(id);
        if (longitudinal == null) {
            return Result.error("纵向课题未找到");
        }
        return Result.success(longitudinal);
    }

    /**
     * 更改纵向课题资料
     */
    @PutMapping("/update")
    @ApiOperation("更改纵向课题资料")
    public Result update(@RequestBody Longitudinal longitudinal) {
        return longitudinalService.updateLongitudinal(longitudinal);
    }

    /**
     * 新增纵向课题资料
     */
    @PostMapping("/save")
    @ApiOperation("新增纵向课题资料")
    public Result addLongitudinal(@RequestBody Longitudinal longitudinal) {
        Result result = longitudinalService.saveLongitudinal(longitudinal);
        return result;
    }

    /**
     * 根据多个id查询纵向课题
     */
    @PostMapping("/getLongitudinalByIds")
    @ApiOperation("通过多个id查询纵向课题信息")
    public Result getLongitudinalByIds(@RequestBody Long[] ids) {
        // 验证传入的ID数组
        if (ids == null || ids.length == 0) {
            return Result.error("未提供有效的纵向课题ID");
        }

        // 调用服务方法，通过ID查询纵向课题
        return longitudinalService.getLongitudinalByIds(ids);
    }


    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_Longitudinal.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("Longitudinal")
                .doWrite(transformedData);
    }

    /**
     * 获取纵向课题汇总
     */
    @GetMapping("/getSummary")
    @ApiOperation("获取纵向课题汇总")
    public Result<List<LongitudinalVO>> getSummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询纵向课题数据
        List<Longitudinal> longitudinalList = longitudinalService.lambdaQuery()
                .eq(Longitudinal::getUserId, userId)
                .select(Longitudinal::getProjectName, Longitudinal::getFundName, Longitudinal::getProjectType,
                        Longitudinal::getGrantingUnit, Longitudinal::getProjectLevel, Longitudinal::getProjectNumber,
                        Longitudinal::getFundingAmount, Longitudinal::getRank, Longitudinal::getStartTime,
                        Longitudinal::getEndTime, Longitudinal::getProjectStatus)
                .list();

        // 将 Longitudinal 转换为 LongitudinalVO
        List<LongitudinalVO> longitudinalVOList = longitudinalList.stream()
                .map(longitudinal -> LongitudinalVO.builder()
                        .projectName(longitudinal.getProjectName())
                        .fundName(longitudinal.getFundName())
                        .projectType(longitudinal.getProjectType())
                        .grantingUnit(longitudinal.getGrantingUnit())
                        .projectLevel(longitudinal.getProjectLevel())
                        .projectNumber(longitudinal.getProjectNumber())
                        .fundingAmount(longitudinal.getFundingAmount())
                        .rank(longitudinal.getRank())
                        .startTime(longitudinal.getStartTime())
                        .endTime(longitudinal.getEndTime())
                        .projectStatus(longitudinal.getProjectStatus())
                        .build())
                .collect(Collectors.toList());

        return Result.success(longitudinalVOList);
    }

    @GetMapping("/getCompletedLongitudinal")
    @ApiOperation("查询结题或者未结题的纵向课题")
    public Result<List<SimpleLongitudinalVO>> getLongitudinal() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询纵向课题数据，选择 id 和 projectName 字段
        List<Longitudinal> longitudinalList = longitudinalService.lambdaQuery()
                .eq(Longitudinal::getUserId, userId)
                .select(Longitudinal::getId, Longitudinal::getProjectName)
                .list();

        // 将 Longitudinal 转换为 SimpleLongitudinalVO 列表，只包含 id 和 projectName 字段
        List<SimpleLongitudinalVO> simpleLongitudinalVOList = longitudinalList.stream()
                .map(longitudinal -> SimpleLongitudinalVO.builder()
                        .id(longitudinal.getId())
                        .projectName(longitudinal.getProjectName())
                        .build())
                .collect(Collectors.toList());

        return Result.success(simpleLongitudinalVOList);
    }

    @GetMapping("/getProjectNameById/{id}")
    @ApiOperation("根据id查询课题名")
    public Result<String> getProjectNameById(@PathVariable Long id) {
        Longitudinal longitudinal = longitudinalService.getLongitudinalById(id);
        if (longitudinal == null) {
            return Result.error("纵向课题未找到");
        }
        return Result.success(longitudinal.getProjectName());
    }

    @GetMapping("/getLongitudinal")
    @ApiOperation("结题助手中查询已结题的纵向课题")
    public Result<List<CompletedLongitudinalVO>> getCompletedLongitudinal() {
        return longitudinalService.getCompletedLongitudinal();
    }


    /**
     * 新增：纵向课题文件解析接口
     * 功能：上传PDF后自动提取字段，返回给前端填充表单
     * @param request 含filePath（PDF转图片的imageBasePath）、pdfPath（原始PDF路径）
     * @return 解析后的Longitudinal + 原始OCR文本
     */
    @PostMapping("/parse")
    public Result<Map<String, Object>> parseLongitudinal(@RequestBody Map<String, String> request) {
        try {
            String filePath = request.get("filePath"); // PDF转图片的路径（用于OCR）
            String pdfPath = request.get("pdfPath");   // 原始PDF文件路径（关联实体）

            // 1. 校验参数
            if (filePath == null || filePath.trim().isEmpty()) {
                return Result.error("纵向课题图片路径不能为空");
            }
            if (pdfPath == null || pdfPath.trim().isEmpty()) {
                return Result.error("纵向课题PDF文件路径不能为空");
            }

            // 2. 提取OCR文本（纵向课题取前4页：封面+立项信息页+基金信息页，避免冗余）
            String ocrText = pdfExtractUtil.extractPdfTextFromImages(filePath, baiduOcrConfig);
            if (ocrText == null || ocrText.trim().isEmpty()) {
                return Result.error("OCR识别失败，未提取到文本");
            }

            // 3. AI解析纵向课题字段（调用工具类新增方法）
            Longitudinal longitudinal = pdfExtractUtil.extractLongitudinalByAi(ocrText, pdfPath);

            // 4. 返回结果给前端（用于填充表单）
            return Result.success(Map.of(
                    "longitudinal", longitudinal, // 解析后的纵向课题数据
                    "rawOcrText", ocrText         // 原始OCR文本（调试用）
            ));

        } catch (Exception e) {
            log.error("纵向课题解析失败", e);
            return Result.error("解析失败：" + e.getMessage());
        }
    }
}
